package com.xueyu.view;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import com.xueyu.dao.BookDao;
import com.xueyu.dao.BookTypeDao;
import com.xueyu.model.Book;
import com.xueyu.model.BookType;
import com.xueyu.util.DbUtil;
import com.xueyu.util.StringUtil;

public class BookManagerInternalFrame extends JInternalFrame {
	private JTextField s_bookNameTxt;
	private JTextField s_authorTxt;
	private JTable bookTable;
	private JComboBox s_bookTypeJcb;

	private DbUtil dbUtil = new DbUtil();
	private BookDao bookDao = new BookDao();
	private BookTypeDao bookTypeDao = new BookTypeDao();
	private JTextField idTxt;
	private JTextField bookNameTxt;
	private JTextField authorTxt;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private JTextField priceTxt;
	private JComboBox bookTypeJcb;
	private JTextArea bookDescTxt;
	private JRadioButton manJrb;
	private JRadioButton womenJrb;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					BookManagerInternalFrame frame = new BookManagerInternalFrame();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public BookManagerInternalFrame() {
		setTitle("图书维护");
		setIconifiable(true);
		setClosable(true);
		setBounds(100, 100, 725, 550);

		JPanel panel = new JPanel();
		panel.setBorder(
				new TitledBorder(null, "\u641C\u7D22\u6761\u4EF6", TitledBorder.LEADING, TitledBorder.TOP, null, null));

		JScrollPane scrollPane = new JScrollPane();
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(
				new TitledBorder(null, "\u8868\u5355\u64CD\u4F5C", TitledBorder.LEADING, TitledBorder.TOP, null, null));

		JButton button_1 = new JButton("修改");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				bookUpdateActionPerformed(e);
			}
		});
		button_1.setIcon(new ImageIcon(BookManagerInternalFrame.class.getResource("/image/modify.png")));

		JButton button_2 = new JButton("删除");
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				bookDeleteActionPerformed(e);
			}
		});
		button_2.setIcon(new ImageIcon(BookManagerInternalFrame.class.getResource("/image/delete.png")));
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup().addContainerGap()
						.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
								.addGroup(groupLayout.createSequentialGroup().addGap(10).addComponent(button_1)
										.addGap(71).addComponent(button_2))
						.addComponent(panel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(scrollPane).addComponent(panel_1, 0, 0, Short.MAX_VALUE))
				.addContainerGap(24, Short.MAX_VALUE)));
		groupLayout
				.setVerticalGroup(
						groupLayout.createParallelGroup(Alignment.LEADING)
								.addGroup(
										groupLayout.createSequentialGroup().addGap(19)
												.addComponent(panel, GroupLayout.PREFERRED_SIZE, 78,
														GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 155,
												GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.RELATED)
				.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 208, GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(ComponentPlacement.UNRELATED).addGroup(groupLayout
						.createParallelGroup(Alignment.BASELINE).addComponent(button_1).addComponent(button_2))
				.addContainerGap(13, Short.MAX_VALUE)));

		JLabel label_2 = new JLabel("图书编号");

		idTxt = new JTextField();
		idTxt.setHorizontalAlignment(SwingConstants.CENTER);
		idTxt.setEditable(false);
		idTxt.setColumns(10);

		JLabel label_3 = new JLabel("图书名称");

		bookNameTxt = new JTextField();
		bookNameTxt.setHorizontalAlignment(SwingConstants.LEFT);
		bookNameTxt.setColumns(10);

		JLabel label_4 = new JLabel("图书作者");

		authorTxt = new JTextField();
		authorTxt.setColumns(10);

		JLabel label_5 = new JLabel("作者性别");

		manJrb = new JRadioButton("男");
		manJrb.setSelected(true);
		buttonGroup.add(manJrb);

		womenJrb = new JRadioButton("女");
		buttonGroup.add(womenJrb);

		JLabel label_6 = new JLabel("图书价格");

		priceTxt = new JTextField();
		priceTxt.setColumns(10);

		JLabel label_7 = new JLabel("图书类别");

		bookTypeJcb = new JComboBox();

		JLabel label_8 = new JLabel("图书描述");

		bookDescTxt = new JTextArea();
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING).addGroup(gl_panel_1
				.createSequentialGroup().addContainerGap()
				.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel_1.createSequentialGroup()
								.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
										.addGroup(gl_panel_1.createSequentialGroup().addComponent(label_2)
												.addPreferredGap(ComponentPlacement.RELATED).addComponent(idTxt,
														GroupLayout.PREFERRED_SIZE, 102, GroupLayout.PREFERRED_SIZE))
								.addGroup(gl_panel_1.createSequentialGroup().addComponent(label_5)
										.addPreferredGap(ComponentPlacement.RELATED).addComponent(manJrb)
										.addPreferredGap(ComponentPlacement.RELATED).addComponent(womenJrb)))
								.addGap(18)
								.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING).addComponent(label_6)
										.addComponent(label_3))
								.addGap(4)
								.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING, false)
										.addComponent(priceTxt)
										.addComponent(bookNameTxt, GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE))
								.addGap(18)
								.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING).addComponent(label_4)
										.addComponent(label_7, GroupLayout.DEFAULT_SIZE, 62, Short.MAX_VALUE))
								.addPreferredGap(ComponentPlacement.RELATED)
								.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
										.addComponent(bookTypeJcb, Alignment.TRAILING, 0, 122, Short.MAX_VALUE)
										.addComponent(authorTxt))
								.addPreferredGap(ComponentPlacement.RELATED, 56, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_panel_1.createSequentialGroup().addComponent(label_8)
								.addPreferredGap(ComponentPlacement.RELATED)
								.addComponent(bookDescTxt, GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)))
				.addGap(15)));
		gl_panel_1.setVerticalGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup().addContainerGap()
						.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE).addComponent(label_2)
								.addComponent(idTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
										GroupLayout.PREFERRED_SIZE)
						.addComponent(label_3)
						.addComponent(bookNameTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
								GroupLayout.PREFERRED_SIZE).addComponent(label_4).addComponent(authorTxt,
										GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
										GroupLayout.PREFERRED_SIZE))
				.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel_1.createSequentialGroup().addGap(18)
								.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
										.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
												.addComponent(label_5).addComponent(manJrb).addComponent(womenJrb))
								.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
										.addComponent(priceTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
												GroupLayout.PREFERRED_SIZE)
										.addComponent(label_7).addComponent(bookTypeJcb, GroupLayout.PREFERRED_SIZE,
												GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))
						.addGroup(gl_panel_1.createSequentialGroup().addGap(18).addComponent(label_6)))
				.addPreferredGap(ComponentPlacement.UNRELATED)
				.addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING)
						.addGroup(gl_panel_1.createSequentialGroup().addComponent(label_8).addContainerGap(89,
								Short.MAX_VALUE))
						.addComponent(bookDescTxt, GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE))));
		panel_1.setLayout(gl_panel_1);

		bookTable = new JTable();
		bookTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				tableMousePressed(e);
			}
		});
		bookTable.setModel(new DefaultTableModel(new Object[][] {},
				new String[] { "\u7F16\u53F7", "\u56FE\u4E66\u540D\u79F0", "\u56FE\u4E66\u4F5C\u8005",
						"\u4F5C\u8005\u6027\u522B", "\u56FE\u4E66\u4EF7\u683C", "\u56FE\u4E66\u63CF\u8FF0",
						"\u56FE\u4E66\u7C7B\u522B" }) {
			boolean[] columnEditables = new boolean[] { false, false, false, false, false, false, false };

			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		bookTable.getColumnModel().getColumn(5).setPreferredWidth(126);
		scrollPane.setViewportView(bookTable);

		JLabel label = new JLabel("图书名称");

		s_bookNameTxt = new JTextField();
		s_bookNameTxt.setColumns(10);

		JLabel lblNewLabel = new JLabel("图书作者");

		s_authorTxt = new JTextField();
		s_authorTxt.setColumns(10);

		JLabel label_1 = new JLabel("图书类别");

		s_bookTypeJcb = new JComboBox();

		JButton button = new JButton("查询");
		button.setIcon(new ImageIcon(BookManagerInternalFrame.class.getResource("/image/search.png")));
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				searchActionePerformed(e);
			}
		});
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
				gl_panel.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel.createSequentialGroup().addContainerGap().addComponent(label)
								.addPreferredGap(ComponentPlacement.RELATED)
								.addComponent(s_bookNameTxt, GroupLayout.PREFERRED_SIZE, 103,
										GroupLayout.PREFERRED_SIZE)
								.addGap(18).addComponent(lblNewLabel).addPreferredGap(ComponentPlacement.RELATED)
								.addComponent(s_authorTxt, GroupLayout.PREFERRED_SIZE, 86, GroupLayout.PREFERRED_SIZE)
								.addGap(18).addComponent(label_1).addPreferredGap(ComponentPlacement.RELATED)
								.addComponent(s_bookTypeJcb, GroupLayout.PREFERRED_SIZE, 114,
										GroupLayout.PREFERRED_SIZE)
								.addGap(18).addComponent(button).addContainerGap(38, Short.MAX_VALUE)));
		gl_panel.setVerticalGroup(gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup().addContainerGap()
						.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE).addComponent(label)
								.addComponent(s_bookNameTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
										GroupLayout.PREFERRED_SIZE)
						.addComponent(s_bookTypeJcb, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
								GroupLayout.PREFERRED_SIZE).addComponent(button)
						.addComponent(label_1)
						.addComponent(s_authorTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
								GroupLayout.PREFERRED_SIZE).addComponent(lblNewLabel))
				.addContainerGap(21, Short.MAX_VALUE)));
		panel.setLayout(gl_panel);
		getContentPane().setLayout(groupLayout);
		// 设置文本域边框
		bookDescTxt.setBorder(new LineBorder(new java.awt.Color(127, 157, 185), 1, false));
		// 初始化table
		fillTable(new Book());
		// 初始化Jcb
		fillJcb("search");
		fillJcb("modify");
	}
	/**
	 * 删除事件处理
	 * @param evt
	 */
	private void bookDeleteActionPerformed(ActionEvent evt) {
		Book book = new Book();
		book.setId(Integer.parseInt(this.idTxt.getText()));
		Connection con = null;
		int ret = JOptionPane.showConfirmDialog(null, "是否删除？");
		if (ret == 0) {
			try {
				con = dbUtil.getCon();
				int n = bookDao.delete(con, book);
				if(n==1){
					JOptionPane.showMessageDialog(null, "删除成功");
					resetValue();
					this.fillTable(new Book());
				}else{
					JOptionPane.showMessageDialog(null, "删除失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(null, "删除失败");
			} finally {
				try {
					dbUtil.closeCon(con);
				} catch (SQLException e) {
					e.printStackTrace();
					JOptionPane.showMessageDialog(null, "somthing wrong");
				}
			}
		}

	}

	/**
	 * 图书修改事件处理
	 * @param evt
	 */
	private void bookUpdateActionPerformed(ActionEvent evt) {
		String id = idTxt.getText();
		String bookName = bookNameTxt.getText();
		String author = authorTxt.getText();
		String sex = "";
		if(manJrb.isSelected()){
			sex = "男";
		}else if(womenJrb.isSelected()){
			sex = "女";
		}
		String price = priceTxt.getText();
		String bookDesc = bookDescTxt.getText();
		BookType bookType = (BookType) bookTypeJcb.getSelectedItem();
		int bookTypeId = bookType.getId();
		if(StringUtil.isEmpty(id)){
			JOptionPane.showMessageDialog(null, "请选择需要修改的图书");
			return;
		}
		if(StringUtil.isEmpty(bookName)){
			JOptionPane.showMessageDialog(null, "图书名称不能为空");
			return;
		}
		if(StringUtil.isEmpty(author)){
			JOptionPane.showMessageDialog(null, "作者不能为空");
			return;
		}
		if(StringUtil.isEmpty(sex)){
			JOptionPane.showMessageDialog(null, "作者性别不能为空");
			return;
		}
		if(StringUtil.isEmpty(price)){
			JOptionPane.showMessageDialog(null, "图书价格不能为空");
			return;
		}else if(!StringUtil.isPrice(price)){
			JOptionPane.showMessageDialog(null, "图书价格格式错误！");
			return;
		}
		Book book = new Book(Integer.parseInt(id), bookName, author, sex, Float.parseFloat(price), bookTypeId,bookDesc);
		Connection con = null;
		try {
			con = dbUtil.getCon();
			int ret = bookDao.update(con, book);
			if(ret==1){
				JOptionPane.showMessageDialog(null, "修改成功");
				fillTable(new Book());
			}else{
				JOptionPane.showMessageDialog(null, "修改失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "修改失败");
		}finally {
			try {
				dbUtil.closeCon(con);
			} catch (SQLException e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(null, "somthing wrong");
			}
		}
	}

	/**
	 * 表格行点击事件处理
	 * 
	 * @param e
	 */
	private void tableMousePressed(MouseEvent e) {
		int row = bookTable.getSelectedRow();
		this.idTxt.setText(bookTable.getValueAt(row, 0) + "");
		this.bookNameTxt.setText(bookTable.getValueAt(row, 1) + "");
		this.authorTxt.setText(bookTable.getValueAt(row, 2) + "");
		String sex = bookTable.getValueAt(row, 3) + "";
		if ("男".equals(sex)) {
			manJrb.setSelected(true);
		} else if ("女".equals(sex)) {
			womenJrb.setSelected(true);
		}
		this.priceTxt.setText(bookTable.getValueAt(row, 4) + "");
		this.bookDescTxt.setText(bookTable.getValueAt(row, 5) + "");
		String bookTypeName = bookTable.getValueAt(row, 6)+"";		
		int n = bookTypeJcb.getItemCount();
		for(int i = 0;i<n;i++){
			BookType item = (BookType) bookTypeJcb.getItemAt(i) ;
			if(item.getBookTypeName().equals(bookTypeName)){
				bookTypeJcb.setSelectedIndex(i);
			}
		}
	}

	/**
	 * 图书查询事件处理
	 * 
	 * @param evt
	 */
	private void searchActionePerformed(ActionEvent evt) {
		String bookName = s_bookNameTxt.getText();
		String author = s_authorTxt.getText();
		BookType bookType = (BookType) s_bookTypeJcb.getSelectedItem();
		int bookTypeId = bookType.getId();
		Book book = new Book();
		book.setBookName(bookName);
		book.setAuthor(author);
		book.setBookTypeId(bookTypeId);
		this.fillTable(book);
	}

	/**
	 * 填充下拉框
	 * @param type区别两个下拉框
	 */
	private void fillJcb(String type) {
		Connection con = null;
		BookType bookType = null;
		try {
			con = dbUtil.getCon();
			ResultSet rs = bookTypeDao.list(con, new BookType());
			if ("search".equals(type)) {
				bookType = new BookType();
				bookType.setId(-1);
				bookType.setBookTypeName("请选择……");
				s_bookTypeJcb.addItem(bookType);
				while (rs.next()) {
					bookType = new BookType();
					bookType.setId(rs.getInt("id"));
					bookType.setBookTypeName(rs.getString("bookTypeName"));
					s_bookTypeJcb.addItem(bookType);
				}
			} else if ("modify".equals(type)) {
				while (rs.next()) {
					bookType = new BookType();
					bookType.setId(rs.getInt("id"));
					bookType.setBookTypeName(rs.getString("bookTypeName"));
					bookTypeJcb.addItem(bookType);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				dbUtil.closeCon(con);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * table表单填充
	 * 
	 * @param book
	 */
	private void fillTable(Book book) {
		DefaultTableModel dtm = (DefaultTableModel) bookTable.getModel();
		dtm.setRowCount(0);
		Connection con = null;
		try {
			con = dbUtil.getCon();
			ResultSet rs = bookDao.list(con, book);
			while (rs.next()) {
				Vector v = new Vector();
				v.add(rs.getString("id"));
				v.add(rs.getString("bookName"));
				v.add(rs.getString("author"));
				v.add(rs.getString("sex"));
				v.add(rs.getString("price"));
				v.add(rs.getString("bookDesc"));
				v.add(rs.getString("bookTypeName"));
				dtm.addRow(v);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				dbUtil.closeCon(con);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 表单重置
	 */
	private void resetValue(){
		this.idTxt.setText("");
		this.authorTxt.setText("");
		this.bookNameTxt.setText("");
		this.priceTxt.setText("");
		manJrb.setSelected(true);
		this.bookDescTxt.setText("");
		this.bookTypeJcb.setSelectedIndex(0);
	}
}
